package secuDropper.core.dropbox;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Locale;

import com.dropbox.core.*;

public class DropboxConnector {

	private final String APP_KEY = "INSERT_APP_KEY_HERE";
	private final String APP_SECRET = "INSERT_APP_SECRET_HERE";
	private DbxAppInfo appInfo;
	private DbxWebAuthNoRedirect webAuth;
	private DbxAuthFinish authFinish;
	private DbxRequestConfig config;
	private String userCode;
	private DbxClient client;

	public DropboxConnector() throws DbxException {
		setupApp();

		if (!checkForExistingUser()) {
			authFinish = authorizeUser();
			writeAuthInfo(authFinish.accessToken);
			registerClient(authFinish.accessToken);
		}

	}

	public DbxClient getClient() {
		return client;
	}

	private DbxAuthFinish authorizeUser() {

		webAuth = new DbxWebAuthNoRedirect(config, appInfo);
		String authorizeUrl = webAuth.start();
		System.out.println("1. Go to: " + authorizeUrl);
		System.out
				.println("2. Click \"Allow\" (you might have to log in first)");
		System.out.println("3. Copy the authorization code.");
		String code;
		try {
			code = new BufferedReader(new InputStreamReader(System.in))
					.readLine().trim();
			return webAuth.finish(code);
		} catch (IOException e1) {
			e1.printStackTrace();
		} catch (DbxException e) {
			e.printStackTrace();
		}
		return null;

	}

	private void writeAuthInfo(String code) {
		BufferedWriter bw;
		try {
			bw = new BufferedWriter(new FileWriter(new File(
					"config/user.properties").getAbsolutePath()));
			bw.write(code);
			bw.flush();
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private boolean checkForExistingUser() {
		BufferedReader br;
		try {
			br = new BufferedReader(new FileReader(new File(
					"config/user.properties").getAbsolutePath()));
			userCode = br.readLine();
			if (userCode == null) {
				br.close();
				return false;
			}
			registerClient(userCode);
			br.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return true;
	}

	private void registerClient(String authToken) {
		client = new DbxClient(config, authToken);
	}

	private void setupApp() {
		appInfo = new DbxAppInfo(APP_KEY, APP_SECRET);
		config = new DbxRequestConfig("secudropper/0.1", Locale.getDefault()
				.toString());
	}

}
